﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace SysCommon
{

    /// <summary>
    /// 读取服务器上的资源
    /// </summary>
    public class IdentityScope : IDisposable
    {

        //using (IdentityScope iss = new IdentityScope("valeb's service", "192.168.1.110", "123"))
        //{ }

          
        /// <summary>
        /// 登录一个新用户
        /// </summary>
        /// <param name="pszUsername"></param>
        /// <param name="pszDomain"></param>
        /// <param name="pszPassword"></param>
        /// <param name="dwLogonType"></param>
        /// <param name="dwLogonProvider"></param>
        /// <param name="phToken"></param>
        /// <returns></returns>
        [DllImport("advapi32.dll", SetLastError = true)]
        static extern bool LogonUser(string pszUsername, string pszDomain, string pszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken);

        //closes open handes returned by LogonUser    
        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        extern static bool CloseHandle(IntPtr handle);

        /// <summary>
        /// 让调用线程模拟一个用户
        /// </summary>
        /// <param name="hToken"></param>
        /// <returns></returns>
        [DllImport("Advapi32.DLL")]
        static extern bool ImpersonateLoggedOnUser(IntPtr hToken);

        /// <summary>
        ///终止模拟的客户应用程序 
        /// </summary>
        /// <returns></returns>
        [DllImport("Advapi32.DLL")]
        static extern bool RevertToSelf();

        public IdentityScope(string Domain,string Username,  string Password)
        {
            // initialize tokens    
            IntPtr pExistingTokenHandle = new IntPtr(0);
            IntPtr pDuplicateTokenHandle = new IntPtr(0);

            try
            {
                // get handle to token    
                bool bImpersonated = LogonUser(Username, Domain, Password, LOGON32_LOGON_NEWCREDENTIALS, LOGON32_PROVIDER_DEFAULT, ref pExistingTokenHandle);


                if (true == bImpersonated)
                {
                    if (!ImpersonateLoggedOnUser(pExistingTokenHandle))
                    {
                        int nErrorCode = Marshal.GetLastWin32Error();
                        throw new Exception("ImpersonateLoggedOnUser error;Code=" + nErrorCode);
                    }
                }
                else
                {
                    int nErrorCode = Marshal.GetLastWin32Error();
                    throw new Exception("LogonUser error;Code=" + nErrorCode);
                }
            }
            finally
            {
                // close handle(s)    
                if (pExistingTokenHandle != IntPtr.Zero)
                    CloseHandle(pExistingTokenHandle);
                if (pDuplicateTokenHandle != IntPtr.Zero)
                    CloseHandle(pDuplicateTokenHandle);
            }
        }

        const int LOGON32_PROVIDER_DEFAULT = 0;

        const int LOGON32_LOGON_NEWCREDENTIALS = 9;

        private bool disposed;

        public void Dispose()
        {
            Dispose(true);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (!disposed)
            {
                RevertToSelf();
                disposed = true;
            }
        }
    }   


     
}
